<template>
  <el-card>
    <!-- 顶部添加按钮 -->
    <el-button type="primary" :icon="Plus" @click="showAddTrademark"
      >添加</el-button
    >
    <!-- 表格展示 -->
    <el-table
      :data="trademarkList"
      border
      class="trademark-table"
      row-key="id"
      v-loading="loading"
    >
      <el-table-column label="序号" type="index" width="60" align="center" />
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column label="品牌LOGO">
        <!-- 使用默认插槽 可以从el-table-column身上获取到 row clumn $index 数据 row是每一行的全部数据 -->
        <template v-slot="{ row }">
          <el-image :src="row.logoUrl" lazy fit="fill" class="trademark-logo">
            <!-- 使用具名插槽 当图片加载失败时显示一个 失败效果图 -->
            <template #error>
              <div class="image-slot">
                <el-icon><icon-picture /></el-icon>
              </div> </template
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot="{ row }">
          <el-button
            type="warning"
            :icon="Edit"
            size="small"
            @click="updateTrademark(row)"
          ></el-button>
          <el-button
            type="danger"
            :icon="Delete"
            size="small"
            @click="open(row.id)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      v-model:current-page="page"
      v-model:page-size="limit"
      :page-sizes="[3, 6, 9]"
      layout=" prev, pager, next, jumper, ->,sizes, total"
      :total="total"
      @size-change="getTrademarkPageList"
      @current-change="getTrademarkPageList"
    />
    <!-- 添加品牌对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="40%"
      :before-close="handleClose"
    >
      <el-form
        label-width="100px"
        :model="addTrademarkFormData"
        :rules="addTrademarkFormDataRules"
        ref="addTrademarkFormRef"
      >
        <!-- prop="tmName" 在 el-form-item 组件上指定校验规则 -->
        <el-form-item label="品牌名称" prop="tmName">
          <el-input
            placeholder="请输入品牌名称"
            class="trademark-Input"
            v-model="addTrademarkFormData.tmName"
          />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <!-- show-file-list="false" 是否可以上传多张图片 -->
          <el-upload
            class="avatar-uploader"
            :action="BASE_URL + `/admin/product/upload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="addTrademarkFormData.logoUrl"
              :src="addTrademarkFormData.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            <!-- 图片上传的提示文本 -->
            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="addTrademark"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 删除品牌对话框 -->
    <!-- <el-button text @click="open">Click to open the Message Box</el-button> -->
  </el-card>
</template>

<script lang="ts">
export default {
  name: "ATrademark",
};
</script>

<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import {
  getTrademarkPageListApi,
  addTrademarkApi,
  getTrademarkInfoApi,
  updateTrademarkApi,
  deleteTrademarkApi,
} from "@/api/product/trademark";
import {
  Plus,
  Edit,
  Delete,
  Picture as IconPicture,
} from "@element-plus/icons-vue";
import type {
  TrademarkList,
  TrademarkInfo,
} from "@/api/product/models/tardemarkModel";
import type { UploadProps } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";

// 上传图片地址的前缀 在 upload 的 action 中 作为请求地址前缀（解决跨域问题）
const BASE_URL = import.meta.env.VITE_API_URL;
// 收集表单数据
const addTrademarkFormData = reactive({
  id: "",
  tmName: "",
  logoUrl: "",
});
// 分页相关数据
const page = ref(1);
const limit = ref(3);
const total = ref(0);
const trademarkList = ref<TrademarkList>([]);
const loading = ref(false);
// 获取form表单实例
const addTrademarkFormRef = ref();
// 表单校验规则
const addTrademarkFormDataRules = reactive({
  tmName: [
    {
      required: true,
      // 校验不通过的提示文本
      message: "请输入品牌名称",
      // 失去焦点时触发校验
      trigger: "blur",
    },
    {
      // 校验字符长度
      min: 2,
      max: 10,
      message: "品牌名称长度必须是 2-10 位",
      trigger: "blur",
    },
  ],
  logoUrl: [
    {
      required: true,
      message: "请上传logo图片",
    },
  ],
});
// 显示/隐藏 添加品牌对话框 -- 标识
const dialogVisible = ref(false);
// 对话框标题
const dialogTitle = ref("");

// 获取品牌管理分页数据
const getTrademarkPageList = async () => {
  loading.value = true;
  const res = await getTrademarkPageListApi(page.value, limit.value);
  loading.value = false;
  trademarkList.value = res.records;
  total.value = res.total;
};
// 挂载获取翻页数据
onMounted(getTrademarkPageList);

// 显示添加品牌 对话框
const showAddTrademark = () => {
  dialogTitle.value = "添加品牌";
  dialogVisible.value = true;
};

// 图片上传成功的回调
const handleAvatarSuccess: UploadProps["onSuccess"] = (response) => {
  // 图片上传成功后 返回图片的在线地址
  addTrademarkFormData.logoUrl = response.data;
  // 清空表单某一个验证规则的 错误提示文本
  addTrademarkFormRef.value.clearValidate(["logoUrl"]);
};
// 图片上传之前的检验
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  // rawFile 上传的源文件
  const validImageTypes = ["image/jpeg", "image/png"];
  if (!validImageTypes.includes(rawFile.type)) {
    ElMessage.error("只能上传jpg/jpge或者png格式的图片!");
    return false;
  } else if (rawFile.size > 500 * 1024) {
    ElMessage.error("上传图片大小不能超过 500kb!");
    return false;
  }
  return true;
};
// 对话框确定按钮 添加/修改 品牌
const addTrademark = async () => {
  try {
    // 手动触发表单校验 validate() 方法的返回值是promise 所有检验通过的结果是true
    await addTrademarkFormRef.value.validate();
    if (dialogTitle.value === "添加品牌") {
      const { tmName, logoUrl } = addTrademarkFormData;
      // 发送请求 添加品牌
      await addTrademarkApi(tmName, logoUrl);
    } else {
      // 发送请求 修改品牌
      await updateTrademarkApi(addTrademarkFormData);
    }
    ElMessage.success(dialogTitle.value + "成功");
    // 关闭对话框
    dialogVisible.value = false;
    // 刷新当前页面数据
    await getTrademarkPageList();
  } catch (error) {
    ElMessage.success(dialogTitle.value + "失败，请按要求填写品牌信息");
  }
};

// 重置表单数据
const resetFormData = () => {
  addTrademarkFormData.id = "";
  addTrademarkFormData.tmName = "";
  addTrademarkFormData.logoUrl = "";
};

// 对话框关闭之前的回调
const handleClose = () => {
  // 清空表单数据
  resetFormData();
  dialogVisible.value = false;
};

// 根据id 获取单个品牌数据
const updateTrademark = async (row: TrademarkInfo) => {
  dialogTitle.value = "修改品牌";
  const res = await getTrademarkInfoApi(row.id);
  Object.assign(addTrademarkFormData, res);
  dialogVisible.value = true;
};

// 点击删除品牌
const open = async (id: number) => {
  try {
    await ElMessageBox.confirm("确定删除 吗?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    // 点击确定按钮 调用删除品牌接口
    await deleteTrademarkApi(id);
    // 重新获取分页数据
    await getTrademarkPageList();
    // 提示用户
    ElMessage({
      type: "success",
      message: "删除成功",
    });
  } catch (error) {
    // 点击取消/关闭对话框 提示用户
    ElMessage({
      type: "info",
      message: "取消操作",
    });
  }
};
</script>

<style scoped>
.trademark-Input {
  width: 400px;
}
.trademark-table {
  margin-top: 20px;
  margin-bottom: 20px;
}
.trademark-logo {
  /* width: 100px; */
  height: 60px;
}
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 30px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader :deep(.el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
